package org.example.redistask;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.nacos.shaded.com.google.common.collect.Maps;

@EnableScheduling
@Component
public class RegisterService implements ApplicationListener<ApplicationStartedEvent>,DisposableBean{
	
	@Autowired
	private RedisTemplate<String,String> rt;
	

	@Autowired
	private ApplicationContext context;
	
	@Scheduled(fixedRate = 5000)
	public void regist() throws UnknownHostException {
		
		Map<String,String> data = getValue();
        rt.boundValueOps(data.get("key")).set(data.get("value"), 10, TimeUnit.SECONDS);
	}

	private Map<String,String> getValue() throws UnknownHostException {
		InetAddress localHost = InetAddress.getLocalHost();
        String ip = localHost.getHostAddress();
        int port = ((AnnotationConfigReactiveWebServerApplicationContext)context).getWebServer().getPort();
        
        String value = ip+":"+port;
        String appName = context.getEnvironment().getProperty("spring.application.name");
//        System.out.println(appName+"本地IP地址：" + value);
        Map<String,String> data = Maps.newHashMap();
        data.put("value", value);
        data.put("key", appName+":"+value);
		return data;
	}

	@Override
	public void onApplicationEvent(ApplicationStartedEvent event) {
		try {
			regist();
			rt.boundSetOps("webServices").add(getValue().get("key"));
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void destroy() throws Exception {
		Map<String,String> data = getValue();
		rt.boundSetOps("webServices").add(data.get("key"));
        rt.delete(data.get("key"));
	}
}
